package com.lean.reptile.spider.sp;

import com.lean.reptile.spider.SpringContextUtil;
import com.lean.reptile.spider.entity.Novel;
import com.lean.reptile.spider.mapper.NovelMapper;
import org.apache.commons.collections.CollectionUtils;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.util.List;

/**
 * 持久化小说数据
 */
public class ZonghengPipeline implements Pipeline {
    private NovelMapper novelMapper = SpringContextUtil.getBean(NovelMapper.class);
    @Override
    public void process(ResultItems resultItems, Task task) {
        //从列表页提取出除小说简介以外的所有信息
        Object novelListObj = resultItems.get("novelList");
        if(null != novelListObj) {
            List<Novel> novelList = (List<Novel>) novelListObj;
            if(CollectionUtils.isNotEmpty(novelList)) {
                for (Novel novel : novelList) {
                    Long id = novel.getId();
                    Novel novel1=novelMapper.findNovelById(id);
                    if(novel1!=null){
                        novelMapper.updateNovel(novel);
                    }else {
                        novelMapper.insertNovel(novel);
                    }
                }
            }
        }
        //从详情页提取出小说简介信息，更新
        Object novelDTOObj = resultItems.get("novelDTO");
        if(null != novelDTOObj) {
            Novel novel = (Novel) novelDTOObj;
            Long id = novel.getId();
            Novel novel1=novelMapper.findNovelById(id);
            if(novel1!=null){
                novelMapper.updateNovel(novel);
            }else {
                novelMapper.insertNovel(novel);
            }
        }
    }
}
